/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-10 09:10:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-10 15:41:04
 * @FilePath: \work-tool\my-dev-project\src\views\system\user.tsx
 * @Description: 用户管理页面
 */
import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, Space, Modal, Form, message } from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LockOutlined,
  UnlockOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;
const { Search } = Input;

// 模拟用户数据
const mockUsers = [
  { id: '1', name: '张三', username: 'zhangsan', email: 'zhangsan@example.com', phone: '13800138001', role: 'admin', status: 'active', createTime: '2025-01-15' },
  { id: '2', name: '李四', username: 'lisi', email: 'lisi@example.com', phone: '13800138002', role: 'editor', status: 'active', createTime: '2025-02-20' },
  { id: '3', name: '王五', username: 'wangwu', email: 'wangwu@example.com', phone: '13800138003', role: 'viewer', status: 'locked', createTime: '2025-03-05' },
  { id: '4', name: '赵六', username: 'zhaoliu', email: 'zhaoliu@example.com', phone: '13800138004', role: 'editor', status: 'active', createTime: '2025-04-10' },
  { id: '5', name: '钱七', username: 'qianqi', email: 'qianqi@example.com', phone: '13800138005', role: 'viewer', status: 'active', createTime: '2025-05-15' },
];

interface User {
  id: string;
  name: string;
  username: string;
  email: string;
  phone: string;
  role: string;
  status: string;
  createTime: string;
}

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>(mockUsers);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState<string>('');
  const [filteredInfo, setFilteredInfo] = useState<Record<string, string | string[] | null>>({});

  // 搜索功能
  const handleSearch = (value: string) => {
    setSearchText(value);
    setFilteredInfo({
      ...filteredInfo,
      name: value || undefined,
    });
  };

  // 过滤信息和排序信息由搜索功能直接更新

  // 打开创建/编辑模态框
  const showModal = (user?: User) => {
    if (user) {
      setEditingUser(user);
      form.setFieldsValue(user);
    } else {
      setEditingUser(null);
      form.resetFields();
    }
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        if (editingUser) {
          // 编辑用户
          const updatedUsers = users.map(user =>
            user.id === editingUser.id ? { ...user, ...values } : user
          );
          setUsers(updatedUsers);
          message.success('用户更新成功');
        } else {
          // 创建用户
          const newUser: User = {
            ...values,
            id: `new_${Date.now()}`,
            createTime: new Date().toISOString().split('T')[0],
          };
          setUsers([...users, newUser]);
          message.success('用户创建成功');
        }
        setIsModalVisible(false);
        form.resetFields();
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 删除用户
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该用户吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        setUsers(users.filter(user => user.id !== id));
        message.success('用户删除成功');
      },
    });
  };

  // 锁定/解锁用户
  const handleToggleStatus = (id: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'locked' : 'active';
    const actionText = newStatus === 'active' ? '解锁' : '锁定';

    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}该用户吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        setUsers(users.map(user =>
          user.id === id ? { ...user, status: newStatus } : user
        ));
        message.success(`用户${actionText}成功`);
      },
    });
  };

  // 表格列配置
  const columns: ColumnsType<User> = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      filteredValue: typeof filteredInfo.name === 'string' ? [filteredInfo.name] : filteredInfo.name,
      onFilter: (value: string, record) => record.name.includes(value),
      sorter: (a, b) => a.name.localeCompare(b.name),
      sortOrder: undefined,
      ellipsis: true,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      ellipsis: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      ellipsis: true,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      ellipsis: true,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      filters: [
        { text: '管理员', value: 'admin' },
        { text: '编辑', value: 'editor' },
        { text: '查看者', value: 'viewer' },
      ],
      onFilter: (value: string, record) => record.role === value,
      render: (role) => {
        let color = '';
        switch (role) {
          case 'admin':
            color = 'red';
            break;
          case 'editor':
            color = 'blue';
            break;
          case 'viewer':
            color = 'green';
            break;
          default:
            color = 'default';
        }
        return <Tag color={color}>{role === 'admin' ? '管理员' : role === 'editor' ? '编辑' : '查看者'}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '激活', value: 'active' },
        { text: '锁定', value: 'locked' },
      ],
      onFilter: (value: string, record) => record.status === value,
      render: (status) => {
        return <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '激活' : '锁定'}
        </Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
      sortOrder: undefined,
    },
    {
      title: '操作',
      key: 'action',
      width: 260,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button size="small" icon={<EditOutlined />} onClick={() => showModal(record)}>
            编辑
          </Button>
          <Button
            size="small"
            icon={record.status === 'active' ? <LockOutlined /> : <UnlockOutlined />}
            onClick={() => handleToggleStatus(record.id, record.status)}
          >
            {record.status === 'active' ? '锁定' : '解锁'}
          </Button>
          <Button
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 过滤后的数据
  const filteredUsers = users.filter(user =>
    (!searchText || user.name.includes(searchText) || user.username.includes(searchText)) &&
    (!filteredInfo.role || user.role === filteredInfo.role)
  );

  return (
    <div style={{ padding: 24 }}>
      <Card
        title="用户管理"
        extra={
          <Space>
            <Search
              placeholder="搜索用户"
              allowClear
              enterButton={<SearchOutlined />}
              size="small"
              onSearch={handleSearch}
            />
            <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
              添加用户
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredUsers}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建/编辑用户模态框 */}
      <Modal
        title={editingUser ? "编辑用户" : "创建用户"}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={editingUser || {
            status: 'active',
            role: 'viewer'
          }}
        >
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名长度不能小于3个字符' }
            ]}

          >
            <Input placeholder="请输入用户名" disabled={!!editingUser} />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="电话"
            rules={[
              { required: true, message: '请输入电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input placeholder="请输入电话" />
          </Form.Item>

          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              <Option value="admin">管理员</Option>
              <Option value="editor">编辑</Option>
              <Option value="viewer">查看者</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">激活</Option>
              <Option value="locked">锁定</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                {editingUser ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;